var baseExtend = "../../script/";

layui.define(['zepto', 'upload'], function (exports) {
  layui.config({
    base: baseExtend
  }).use(['justchatSocketMgr', 'justchatApiMgr', 'storage'], function () {
    var justchatApiMgr = layui.justchatApiMgr;
    var $ = layui.zepto;
    var upload = layui.upload
    var $outer = $('#otherPage');
    $outer.on('complaintInit', complaintInit);

    function complaintInit() {
      var data = {
        imgs: [] // 上传后的地址
      };
      var uploads = []; // 上传后的img元素。

      __pageInit();
      __selectInit();
      __describleInit();
      __uploadInit();

      function __pageResultInit(type) {
        if (!type) throw new Error('参数不齐全');
        var tip = (type === 'success' ? '官方团队会尽快核实，并通过邮件通知您处理结果。感谢您的支持。' : '当前网络异常，请稍后再试。');
        var temp = `
      <div class="complaint">
        <i class="result-icon result-icon-${type} ${type==='success'?'layui-icon-ok':'layui-icon-close'} layui-icon"></i>
        <p class="tip">${tip}</p>
        <button id="close" class="layui-btn submit">关闭</button>
      </div>
      `

        $outer.find('#content').html(temp);

        $outer.find('#close').on('click', function () {
          $outer.hide();
        })
      }

      function __pageInit() {
        $outer.find('#head p').text('代理投诉');
        $outer.find('#head .goback').on('click', function () {
          $outer.hide();
        })
        var temp = `
          <div class="complaint">
            <div class="complaint-item">
                <p class="title">请选择投诉代理的原因（必填）：</p>
                <div class="myselect" id="complaint-select">
                  <div class="myselect-input">
                    <p class="value">请选择投诉原因</p>
                    <i class="myselect-icon myselect-noactive layui-icon layui-icon-triangle-d"></i>
                    <i class="myselect-icon myselect-active layui-icon layui-icon-triangle-r"></i>
                  </div>
                  <ul class="myselect-option layui-hide">
                    <li data-value='1'>充值未到账</li>
                    <li data-value='2'>态度恶劣</li>
                    <li data-value='5'>给其他游戏打广告</li>
                    <li data-value='6'>不当言论</li>
                    <li data-value='4'>其他</li>
                  </ul>
                </div>
            </div>
            <div class="complaint-item">
                <p class="title">投诉内容（必填）：</p>
                <textarea id="describle"  maxlength="200" class="describle" placeholder="请输入投诉问题描述（200字以内）"></textarea>
            </div>
            <div class="complaint-item">
                <p class="title">图片证据（必填，可提交3张）：</p>
                <div class="picupload">
                    <div id="imgBox"></div>
                    <div class="uploadbtn" id="uploadbtn">
                      <i class="layui-icon layui-icon-add-1 icon"></i>
                    </div>
                </div>
            </div>
            <button id="submit" class="layui-btn submit layui-disabled">提交</button>
          </div>
          `

        $outer.find('#content').html(temp);
        $outer.find('#submit').on('click', function () {
          if ($(this).hasClass('layui-disabled')) return
          justchatApiMgr.complain({
            target_id: Number(window.currentTarget),
            images: data.imgs,
            complaint_content: data.content,
            complaint_types: Number(data.select)
          }, function (res) {
            if (res.status == 0) {
              var imid = getParam('imid');
              var compaint_date = layui.data('complaint_time') || {};
              var cur_compaint_date = compaint_date[imid] || {}
              cur_compaint_date[window.currentTarget] = layui.data.date().split(' ')[0];
              __pageResultInit('success');
              layui.data('complaint_time', {
                key: imid
                , value: cur_compaint_date
              });
              $('#go-complaint').hide();
            } else {
              __pageResultInit('error')
            }
          }, function () {
            __pageResultInit('error')
          })
        })
      }

      function getParam(paramName) {
        var paramValue = "", isFound = !1;
        if (window.location.search.indexOf("?") == 0 && window.location.search.indexOf("=") > 1) {
            var arrSource = unescape(window.location.search).substring(1, window.location.search.length).split("&"), i = 0;
            while (i < arrSource.length && !isFound) arrSource[i].indexOf("=") > 0 && arrSource[i].split("=")[0].toLowerCase() == paramName.toLowerCase() && (paramValue = arrSource[i].split("=")[1], isFound = !0), i++
        }
        return paramValue == "" && (paramValue = null), paramValue
      };

      function __selectInit() {
        var $select = $("#complaint-select");
        var $value = $select.find('.value');
        var $options = $select.find('.myselect-option');

        $outer.on('click', function () {
          $options.addClass('layui-hide');
        })
        $select.find('.myselect-input').on('click', function (event) {
          $options.toggleClass('layui-hide');
          event.stopPropagation();
        })
        $select.find('.myselect-option').on('click', 'li', function (event) {
          $value.text(this.innerText);
          data.select = this.getAttribute('data-value');
          __validate();
          $options.toggleClass('layui-hide');
          event.stopPropagation();
        })
      }

      function __describleInit() {
        $('#describle').on('input', function () {
          data.content = this.value;
          __validate();
        })
      }

      function __validate() {
        var $submit = $outer.find('#submit');
        if (data.select && data.content && (data.imgs.length>0)) {
          $submit.removeClass('layui-disabled');
        } else {
          $submit.addClass('layui-disabled');
        }
      }

      function __uploadInit() {
        upload.render({
          elem: '#uploadbtn',
          url: '',
          multiple: true,
          number: 3,
          acceptMime: 'image/*',
          accept: 'images',
          auto: false,
          done: function (res, index, upload) { //上传后的回调

          },
          choose: function (obj) {
            if (uploads.length >= 3) return
            // 打开加载
            layer.load({
              icon: 1,
            });
            obj.preview(function (index, f, result) {
              //创建新文件对象（实现更名）
              // var fileName = new Date().getTime() + f.name.substring(f.name.lastIndexOf('.'))
              __upload(f, result);
            })
          },
        })
      }

      // 上传
      function __upload(file, base64) {
        var $imgBox = $outer.find('#imgBox');
        var $uploadbtn = $outer.find('#uploadbtn');

        var config = {
          useCdnDomain: true,
          disableStatisticsReport: false,
          retryCount: 6
        };
        var putExtra = {
          fname: "",
          params: {},
          mimeType: null
        };
        // 获取七牛上传token
        justchatApiMgr.getToken(function (result) {
          var token = result.data.token;
          var key = result.data.key;
          // 上传
          var observable = qiniu.upload(file, key, token, putExtra, config);
          var subObject = {
            next: function (response) {

            },
            error: function (err) {
              // 关闭加载
              layer.closeAll('loading');
            },
            complete: function (res) {
              console.log("download:key=" + key);

              // 获取地址
              justchatApiMgr.getURL(key, function (r) {
                var d = r.data;
                var urls = d.urls;
                var url = (/[0-9]{4}\/[0-9]{2}\/[0-9]{2}\/.+/g.exec(urls[0].url))[0];
                data.imgs.push(url);
                __validate();

                var img = __imgTemp(base64);
                uploads.push(img);
                if (uploads.length >= 3) {
                  $uploadbtn.hide();
                }
                $imgBox.append(img);
                // 关闭加载
                layer.closeAll('loading');
              })
            }
          };
          var subscription = observable.subscribe(subObject);
        }, function (err) {
          // 关闭加载
          layer.closeAll('loading');
        });
      }

      function __imgTemp(url) {
        var img = $(`
        <div class="img-box" style="position:relative;margin-right:15px;display:inline-block;">
          <img src="${url}" style="display:block;height:64px;width:64px;">
          <i class="remove-img layui-icon-close layui-icon" style="z-index:19891016;border-radius:50%;;text-align:center;line-height:20px;position:absolute;right:-10px;top:-10px;width:20px;height:20px;font-size:16px;background:red;color:#fff;"></i>
        </div>
      `)
        img.on('click', '.remove-img', __removeImg)
        return img
      }

      function __removeImg() {
        var $uploadbtn = $outer.find('#uploadbtn');
        var index = $(this).closest('.img-box').index();
        uploads.splice(index, 1)[0].remove();
        data.imgs.splice(index, 1);
        __validate();
        $uploadbtn.show();
      }

    }

    exports('complaint', complaintInit);
  })

});